<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;
use app\common\model\BaziPaipanLog;

/**
 * 八字排盘接口
 * @ApiWeigh (98)
 */
class BaziPaipan extends Api
{
    protected $noNeedLogin = [];  // 修改为需要登录
    protected $noNeedRight = '*';

    /**
     * 八字排盘
     * 
     * @ApiTitle    (八字排盘)
     * @ApiSummary  (根据生辰八字信息进行八字排盘分析)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/bazi_paipan/index)
     * 
     * @ApiParams   (name="name", type="string", required=true, description="姓名")
     * @ApiParams   (name="sex", type="integer", required=true, description="性别：0=男，1=女")
     * @ApiParams   (name="type", type="integer", required=true, description="历法类型：0=农历，1=公历")
     * @ApiParams   (name="year", type="integer", required=true, description="出生年，如：1988")
     * @ApiParams   (name="month", type="integer", required=true, description="出生月，如：8")
     * @ApiParams   (name="day", type="integer", required=true, description="出生日，如：7")
     * @ApiParams   (name="hours", type="integer", required=true, description="出生时，24小时制，如：12")
     * @ApiParams   (name="minute", type="integer", required=true, description="出生分，如：30")
     * @ApiParams   (name="sect", type="integer", required=false, description="流派：1=晚子时日柱算明天，2=晚子时日柱算当天", default=2)
     * @ApiParams   (name="zhen", type="integer", required=false, description="是否考虑真太阳时：1=是，2=否", default=2)
     * @ApiParams   (name="province", type="string", required=false, description="出生省份，如：北京市")
     * @ApiParams   (name="city", type="string", required=false, description="出生城市，如：北京")
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "name": "张三",                    // 姓名
          "gender": "男",                    // 性别
          "birth_date": "1988年8月7日",      // 出生日期
          "birth_time": "12时30分",          // 出生时间
          "lunar_date": "戊辰年六月廿五",     // 农历日期
          "bazi": "戊辰 己未 甲午 丙午",      // 八字
          "wuxing": "土土木火",              // 五行
          "sizhu": {                        // 四柱
            "year": "戊辰",                  // 年柱
            "month": "己未",                 // 月柱
            "day": "甲午",                   // 日柱
            "hour": "丙午"                   // 时柱
          },
          "shishen": ["伤官","偏财","日主","伤官"], // 十神
          "dayun": [{                       // 大运
            "age": "0-7",                   // 年龄范围
            "ganzhi": "庚申",               // 干支
            "shishen": "正财"               // 十神
          }],
          "analysis": {                     // 命盘分析
            "remark": "命盘分析说明...",      // 分析说明
            "advantage": "优势...",          // 优势
            "disadvantage": "劣势..."        // 劣势
          }
        }
      })
     */
    public function index()
    {
        $params = [
            'name' => $this->request->post('name', '', 'trim'),
            'sex' => $this->request->post('sex', 0, 'intval'),
            'type' => $this->request->post('type', 0, 'intval'),
            'year' => $this->request->post('year', '', 'intval'),
            'month' => $this->request->post('month', '', 'intval'),
            'day' => $this->request->post('day', '', 'intval'),
            'hours' => $this->request->post('hours', '', 'intval'),
            'minute' => $this->request->post('minute', '', 'intval'),
            'sect' => $this->request->post('sect', 2, 'intval'),
            'zhen' => $this->request->post('zhen', 2, 'intval'),
            'province' => $this->request->post('province', '', 'trim'),
            'city' => $this->request->post('city', '', 'trim')
        ];

        // 必填参数验证
        $required = ['name', 'sex', 'type', 'year', 'month', 'day', 'hours', 'minute'];
        foreach ($required as $field) {
            if (!isset($params[$field])) {
                $this->error(__('Parameter %s can not be empty', $field));
            }
        }

        // 参数验证
        if (!in_array($params['sex'], [0, 1])) {
            $this->error(__('Invalid sex value'));
        }
        if (!in_array($params['type'], [0, 1])) {
            $this->error(__('Invalid type value'));
        }
        if (!in_array($params['sect'], [1, 2])) {
            $this->error(__('Invalid sect value'));
        }
        if (!in_array($params['zhen'], [1, 2])) {
            $this->error(__('Invalid zhen value'));
        }

        try {
            $result = YuanfenjuService::instance()->request('/Bazi/paipan', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '八字排盘失败');
            }
            
            // 记录查询日志
            BaziPaipanLog::create([
                'user_id' => $this->auth->id,
                'name' => $params['name'],
                'gender' => $params['sex'],
                'type' => $params['type'],
                'birth_info' => json_encode([
                    'year' => $params['year'],
                    'month' => $params['month'],
                    'day' => $params['day'],
                    'hours' => $params['hours'],
                    'minute' => $params['minute']
                ], JSON_UNESCAPED_UNICODE),
                'sect' => $params['sect'],
                'zhen' => $params['zhen'],
                'province' => $params['province'],
                'city' => $params['city'],
                'response_data' => json_encode($result['data'], JSON_UNESCAPED_UNICODE)
            ]);
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }

    /**
     * 查询历史列表
     * 
     * @ApiTitle    (八字排盘历史记录)
     * @ApiSummary  (获取用户的八字排盘查询历史记录)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/bazi_paipan/history)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="limit", type="integer", required=false, description="每页数量", default=10)
     * 
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "获取成功",
     *   "time": "1677123456",
     *   "data": {
     *     "total": 100,                     // 总记录数
     *     "list": [{
     *       "id": 1,                        // 记录ID
     *       "name": "张三",                 // 姓名
     *       "sex": 0,                       // 性别 0=男,1=女
     *       "type": 1,                      // 历法类型 0=农历,1=公历
     *       "birth_info": {                 // 出生信息
     *         "year": 1988,                 // 出生年
     *         "month": 8,                   // 出生月
     *         "day": 7,                     // 出生日
     *         "hours": 12,                  // 出生时
     *         "minute": 30                  // 出生分
     *       },
     *       "sect": 2,                      // 流派 1=晚子时日柱算明天,2=晚子时日柱算当天
     *       "zhen": 2,                      // 是否真太阳时 1=是,2=否
     *       "province": "北京市",           // 出生省份
     *       "city": "北京",                 // 出生城市
     *       "createtime": 1677123456,       // 创建时间戳
     *       "createtime_text": "2023-02-23 12:34:56" // 创建时间文字
     *     }]
     *   }
     * })
     */
    public function history()
    {
        $page = $this->request->get('page', 1, 'intval');
        $limit = $this->request->get('limit', 10, 'intval');
        
        $total = BaziPaipanLog::where('user_id', $this->auth->id)->count();
        $list = BaziPaipanLog::where('user_id', $this->auth->id)
            ->field('id,name,gender as sex,type,birth_info,sect,zhen,province,city,createtime')
            ->order('id desc')
            ->page($page, $limit)
            ->select();
            
        foreach ($list as &$item) {
            $item['birth_info'] = json_decode($item['birth_info'], true);
        }
        
        $this->success('获取成功', [
            'total' => $total,
            'list' => $list
        ]);
    }

    /**
     * 查询历史详情
     * 
     * @ApiTitle    (八字排盘历史详情)
     * @ApiSummary  (获取指定八字排盘记录的详细信息)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/bazi_paipan/detail)
     * @ApiParams   (name="id", type="integer", required=true, description="记录ID")
     * 
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "获取成功",
     *   "time": "1677123456",
     *   "data": {
     *     "id": 1,                          // 记录ID
     *     "user_id": 1,                     // 用户ID
     *     "name": "张三",                   // 姓名
     *     "gender": 0,                      // 性别 0=男,1=女
     *     "type": 1,                        // 历法类型 0=农历,1=公历
     *     "birth_info": {                   // 出生信息
     *       "year": 1988,                   // 出生年
     *       "month": 8,                     // 出生月
     *       "day": 7,                       // 出生日
     *       "hours": 12,                    // 出生时
     *       "minute": 30                    // 出生分
     *     },
     *     "sect": 2,                        // 流派 1=晚子时日柱算明天,2=晚子时日柱算当天
     *     "zhen": 2,                        // 是否真太阳时 1=是,2=否
     *     "province": "北京市",             // 出生省份
     *     "city": "北京",                   // 出生城市
     *     "createtime": 1677123456,         // 创建时间戳
     *     "createtime_text": "2023-02-23 12:34:56", // 创建时间文字
     *     "response_data": {                // 排盘结果数据
     *       // ... 同八字排盘接口返回的data部分
     *     }
     *   }
     * })
     */
    public function detail()
    {
        $id = $this->request->get('id', 0, 'intval');
        
        $log = BaziPaipanLog::where('user_id', $this->auth->id)
            ->where('id', $id)
            ->find();
            
        if (!$log) {
            $this->error('记录不存在');
        }
        
        $log['birth_info'] = json_decode($log['birth_info'], true);
        $log['response_data'] = json_decode($log['response_data'], true);
        
        $this->success('获取成功', $log);
    }
    /**
     * 清空历史记录
     * 
     * @ApiTitle    (清空八字排盘历史记录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/bazi_paipan/clearHistory)
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "清空成功",
     *   "data": null
     * })
     */
    public function clearHistory()
    {
        try {
            BaziPaipanLog::where('user_id', $this->auth->id)->delete();
            $this->success('清空成功');
        } catch (\think\exception\PDOException $e) {
            $this->error('清空失败：' . $e->getMessage());
        }
    }

}